(function($){
	$.fn.extend({
	   tabs : function(config){	   
	    var defaults=config||{};
		return this.each(function(){
			var obj=this;	
			var items = $("li", obj);
			items.each(function(){
				 $(this).click(function(){
					 items.each(function(){
						$(this).removeClass("active");
						$("#"+this.id+"-content").css("display", "none");
					  });
					  
					 $(this).addClass("active");
					 $("#"+this.id+"-content").css("display", "");					 
			    });
			 });
		
		  })
	   }
	});
  
  //------------------------
  
	var handleInput=function(evt) {
		if(evt.type == 'keyup' && evt.keyCode!=13){
			handleInputSuggest(evt);
		}else{	
		   handleInputEvaluate(evt);
		}
	}

	var lastLookup="";
	var handleInputSuggest=function(evt) {	
		var url='../jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.dumpObjectProperties}'
		var lookup;
		var exp=$("#jsfdump-expression").val();
		//Checks if the user have ${ typed in
		var startRegex = /\${\B/
		if(exp.match(regexp)!=null){
			lookup=exp;
		}

		//Matches    ${property.  
		var regexp = /\${((.*?)\.)+/
		
		if(exp.match(regexp)!=null){
			lookup=exp.match(regexp)[0];
			//Replace last . with } so we can evaluate ${bean.prop} , should fix that via regex		
			lookup=lookup.substring(0,lookup.length-1)+"}";
		}else{
			$("#jsfdump-suggestion").css("display", "none");
			return;
		}
	    //cached result
		if(lookup==lastLookup){
			$("#jsfdump-suggestion").css("display", "");
			var props=exp.split(".");
			var property=props[props.length-1];
			var filtered=$.grep(lastLookedupItems, function(item){
				return (item.indexOf(property) > -1);
			});
			//Nothing to show so hide our lookup
			if(filtered.length==0){
				$("#jsfdump-suggestion").css("display", "none");
			}else{
				updateSuggestions(filtered);
			}
			return;
		}
		
		$.ajax({
		   type: "GET",
		   url: url,
		   beforeSend : function (xhr) {//Request with jsf-console header will not be tracked
			  xhr.setRequestHeader('JSF-Console', 'true');
		   },

		   data: {p1:lookup},
		   success: function(data){
		   
			 var x = $("#jsfdump-expression").offset().left;
			 var y = $("#jsfdump-expression").offset().top;
			 
			 var height = document.getElementById('jsfdump-expression').offsetHeight;
			 var fieldWidth = document.getElementById('jsfdump-expression').offsetWidth;
 
			 $("#jsfdump-suggestion").css("left", x);
			 $("#jsfdump-suggestion").css("top", y+height);
			 $("#jsfdump-suggestion").css("width", fieldWidth+"px");
			 $("#jsfdump-suggestion").css("display", "");			 
			 
			    lastLookedupItems=data.split(",");
				updateSuggestions(lastLookedupItems);
		   }
		 });
		
		lastLookup=lookup;		
	}
	var lastLookedupItems=[];
	var updateSuggestions=function(items){
		var str=[];
				str[str.length] = "<ul class='jsfdump-sugesstion'>";
				for(var i=0;i<items.length;i++){
					var item=items[i];
					str[str.length] = "<li  class='jsfdump-sugesstion-item'>";
					str[str.length] = "<a href='javascript:void(0);'  onclick=\"evalExpresession('"+item+"')\" >";
//					str[str.length] = "<a href='javascript:void(0);' onfocus='suggestionFocus(this)'  onblur='suggestionBlur(this)'  onclick=\"evalExpresession('"+item+"')\" >";
					str[str.length] = item;
					str[str.length] = "</a>";
					str[str.length] = "</li>";  
				 }; 
				str[str.length] = "</ul>";			    
				$("#jsfdump-suggestion-content").html(str.join("")); 	
	};
	

	
	
	var handleInputEvaluate=function(evt) {
		var exp=$("#jsfdump-expression").val();
		//var url='http://localhost:8080/JSFDumpDemo/jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.dump}&p1=${beeHive.honey}';
		var url='../jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.dump}';
		
		   
		$.ajax({
		   type: "GET",
		   url: url,
		   beforeSend : function (xhr) {//Request with jsf-console header will not be tracked
			  xhr.setRequestHeader('JSF-Console', 'true');
		   },
		   data:  {p1:exp}, 
		   success: function(data){
			 $("#console-panelDisplay").html(data);
		   }
		 });
		 
		   
		   /*
		 $("#jsfdump-expression").load(url, 
		  
		   function(data){
				
		 });
		 */
		 
	};
			 
		var handleScopeTypeClick=function(chkbox){
			var target=arguments[0].target;
			var checkedItems=[];
			
	
			$('input:checkbox[name=jsfconsole-scopetype]').each(function(){ 
			
				if(this.checked){
					checkedItems.push(this.value);
				}
			});
			var url='../jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.dumpResolvableProperties}';
			
			$.ajax({
			   type: "GET",
			   url: url,
			   beforeSend : function (xhr) {//Request with jsf-console header will not be tracked
				  xhr.setRequestHeader('JSF-Console', 'true');
			   },
			   data: {p1: checkedItems.toString()}, 
			   success: function(data){
				   var response = data;
				   var container=$('#bean-container');
				   var str=[];
				   str[str.length] = "<table class='jsfdump-beanlist' style='width:100%'>";
				   str[str.length] = "<th style='text-align:left'>Bean</th> <th style='text-align:left'>Scope</th>";
				   
				   
				   var items=response.split(",");
				  
				  for(var i=0;i<items.length;i++){
					var item=items[i];
					var sItem=item.split(":");
					var itemName=sItem[0];
					var itemScope=sItem[1];
					var color=(i%2==0)?"DEE0D5":"E6E7E8";
					str[str.length] = "<tr  class='jsfdump-beanlist-item' style='background:#"+color+";'>";
					str[str.length] = "<td>";
					str[str.length] = "<a href='javascript:void(0);'   onclick=\"evalExpresession('"+itemName+"')\" class='jsfdump-scope-"+itemScope+"'>"
					str[str.length] = itemName;
					str[str.length] = "</a>";
					str[str.length] = "</td><td>";
					str[str.length] = itemScope;
					str[str.length] = "</td>";
					
					str[str.length] = "</tr>";
				   }
				   
					str[str.length] = "</table>";			    
					container.html(str.join(""));				
				}
			   
			 });
		 
		 
		};
			  
		var monitoringState=false;
		var handleLifecycleMonitor=function(e){
			monitoringState=!monitoringState;		
			var btn=$("#jsfdump-lifecycle-monitor");						

			if(monitoringState){
				btn.val("Stop Monitoring");
				handleLifecycleStartMonitor(e);
			}else{
				btn.val("Start Monitoring");
				handleLifecycleEndMonitor(e);
			}			
		};
		

			
			
		var lifecycleUpdateCycle=0; 
		var lifecycleUpdateInterval=0;
		var handleLifecycleStartMonitor=function(e){			
			lifecycleUpdateCycle=$("#jsfdump-lifecycle-interval").val();
			lifecycleUpdateCycle=lifecycleUpdateCycle*1000;
			
		   //Start monitor 
		   var url='../jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.startMonitoringLifecycle}';
			 $.ajax({
			  type: "GET",
			   url: url,	 
				beforeSend : function (xhr) {//Request with jsf-console header will not be tracked
				  xhr.setRequestHeader('JSF-Console', 'true');
			   }
			});
		
			
			var updateLifecycle=function(){	
				Indicator.start();
				var url='../jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.showEvents}';
				  $.ajax({
				   type: "GET",
				   url: url,	 
				    beforeSend : function (xhr) {//Request with jsf-console header will not be tracked
					  xhr.setRequestHeader('JSF-Console', 'true');
				   },
		   
				   data: {p1:'/', p2:lifecycleViewType},				   
				   success: function(data){
							$('#lifecycle-container').html(data);
							Indicator.stop();
						  }				 
					});
			};
			lifecycleUpdateInterval = setInterval(updateLifecycle, lifecycleUpdateCycle);
		};
		
		
		var handleLifecycleEndMonitor=function(e){
			clearInterval(lifecycleUpdateInterval);
			//End  monitor
		   var url='../jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.stopMonitoringLifecycle}';
		   $.ajax({
				   type: "GET",
				   url: url,	
				    beforeSend : function (xhr) {//Request with jsf-console header will not be tracked
							  xhr.setRequestHeader('JSF-Console', 'true');
				   },				   
				   success: function(data){
				   
					}				 
				});
			
		};




	function initalizeLogViewer(){
		   var logInterval=0;
			var updateLifecycle=function(){	 
				Indicator.start();
				var url='../jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.showEventLog}';
				  $.ajax({
				   type: "GET",
				   url: url,	 
				    beforeSend : function (xhr) {//Request with jsf-console header will not be tracked
					  xhr.setRequestHeader('JSF-Console', 'true');
				   },
				   data: {p1:0},/*Request ID =0 newest request*/				   
				   success: function(data){
							$('#console-eventlog').html(data);
							Indicator.stop();
						  }				 
					});
					
			
				var url='../jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.showEventLogRequest}';
				  $.ajax({
				   type: "GET",
				   url: url,	 
				    beforeSend : function (xhr) {//Request with jsf-console header will not be tracked
					  xhr.setRequestHeader('JSF-Console', 'true');
				   },
				   data: {p1:0},/*Request ID =0 newest request*/				   
				   success: function(data){
							$('#console-eventlog-request').html(data);
							Indicator.stop();
						  }				 
					});
					
			};
			logInterval = setInterval(updateLifecycle, 2500);
		}
		
	  function initalizeValidationViewer(){
		   var logInterval=0;
			var updateLifecycle=function(){	
				Indicator.start();
				var url='../jsfconsole/ajax/ajaxHandler.jsf?exp=${ajaxHandler.showValidationLog}';
				  $.ajax({
				   type: "GET", 
				   url: url,	 
				    beforeSend : function (xhr) {//Request with jsf-console header will not be tracked
					  xhr.setRequestHeader('JSF-Console', 'true');
				   },
				 data: {p1:validationViewType},/*Request ID =0 newest request*/				   
			   
				   success: function(data){
							$('#console-validation').html(data);
							Indicator.stop();
						  }				 
					});
			};
			logInterval = setInterval(updateLifecycle, 3000);
		}
		
	  
	$(document).ready(function(){
		$('#navigation-tabs').tabs({});
		
		$("#jsfdump-eval").bind("click", handleInput);
		$("#jsfdump-expression").bind("keyup", handleInput);
			
		//LifeCycle
		$("#jsfdump-lifecycle-monitor").bind("click", handleLifecycleMonitor);
		
		initalizeLogViewer();
	 
		initalizeValidationViewer();
		//Bean Manager
		$('input:checkbox[name=jsfconsole-scopetype]').bind("click", handleScopeTypeClick);
			
	/*
		/	/jsf-dump-lifecycle-interval
				
			//LifeCycle
			$("jsfdump-lifecycle-start").observe("click", handleLifecycleStartMonitor);
			$("jsfdump-lifecycle-end").observe("click", handleLifecycleEndMonitor);
			
			*/
			
	});
  
})(jQuery);


function evalExpresession(item){
	var exp="${"+item+"}";
	$("#jsfdump-expression").val(exp);
	$("#jsfdump-expression").click();
}

var validationViewType='expanded';
var lifecycleViewType='expanded';

function lifecycleView(type){
	lifecycleViewType=type;
}
function validationView(type){
	validationViewType=type;
}
  
  
 function updatePhaseGraph(times){	
	var surl="http://chart.apis.google.com/chart?cht=p3&chd=t:"+times+"&chs=500x100&chl=RESTORE_VIEW|APPLY_REQUEST_VALUES|PROCESS_VALIDATIONS|UPDATE_MODEL_VALUES|INVOKE_APPLICATION|RENDER_RESPONSE";
	$("#jsfdump-phase-graph").attr("src", surl);
 };
 
 
var Indicator=function(){
	return{
		start:function(){
			$("#indicator").css("display", "");
		},
		stop:function(){
			$("#indicator").css("display", "none");
		}
	};
}();